import streamlit as st
import os
import shutil
import database as db
import time
from datetime import datetime

def render():
    """渲染文件上传界面"""
    st.title("文件上传")
    
    # 上传视频文件
    uploaded_file = st.file_uploader("选择视频文件", type=["mp4", "avi", "mov", "mkv"], accept_multiple_files=False)
    
    if uploaded_file is not None:
        # 显示文件信息
        file_details = {
            "文件名": uploaded_file.name,
            "文件类型": uploaded_file.type,
            "文件大小": f"{uploaded_file.size / (1024 * 1024):.2f} MB"
        }
        
        st.write("文件信息:")
        for k, v in file_details.items():
            st.write(f"- **{k}**: {v}")
        
        # 保存文件
        if st.button("保存文件"):
            save_uploaded_file(uploaded_file)
    
    # 显示已上传的视频列表
    display_uploaded_videos()

def save_uploaded_file(uploaded_file):
    """保存上传的文件并记录到数据库"""
    # 确保上传目录存在
    os.makedirs("data/uploads", exist_ok=True)
    
    # 生成唯一文件名（时间戳+原始文件名）
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"{timestamp}_{uploaded_file.name}"
    file_path = os.path.join("data/uploads", filename)
    
    # 保存文件
    with open(file_path, "wb") as f:
        f.write(uploaded_file.getbuffer())
    
    # 保存到数据库
    user_id = st.session_state.user['id']
    video_id = db.add_video(uploaded_file.name, file_path, user_id)
    
    if video_id:
        st.success(f"文件 '{uploaded_file.name}' 上传成功！")
        time.sleep(1)
        st.rerun()
    else:
        st.error("文件上传失败，请重试。")

def display_uploaded_videos():
    """显示已上传的视频文件列表"""
    st.subheader("已上传的视频")
    
    # 根据用户权限获取视频列表
    if st.session_state.user['is_admin']:
        # 管理员可以看到所有视频
        videos = db.get_videos()
    else:
        # 普通用户只能看到自己上传的视频
        user_id = st.session_state.user['id']
        videos = db.get_videos(user_id)
    
    if not videos:
        st.info("暂无上传的视频")
        return
    
    # 显示视频列表
    for video in videos:
        col1, col2, col3, col4 = st.columns([3, 2, 2, 1])
        
        with col1:
            st.write(f"**{video['filename']}**")
        
        with col2:
            st.write(f"上传者: {video['uploader']}")
        
        with col3:
            status = "已处理" if video['processed'] else "未处理"
            st.write(f"状态: {status}")
        
        with col4:
            # 查看详情按钮
            if st.button("详情", key=f"detail_{video['id']}"):
                st.session_state.selected_video_id = video['id']
                st.session_state.selected_video_path = video['original_path']
                st.session_state.current_page = "detection"
                st.rerun() 